﻿using DataAccess;
using log4net.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.FileProviders;
using MyPetHub.Common;
using MyPetHub.Controllers;
using MyPetHub.Filters;
using MyPetHub.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.DrawingCore;
using System.DrawingCore.Imaging;
using System.Linq.Expressions;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
using System.Transactions;
using Color = System.DrawingCore.Color;

namespace MyPetHub.Areas.Admin.Controllers
{
    [Area("Admin")]
    [AdminAuthorizationFilter]
    public class AdminHomeController : BaseController
    {
        IFileProvider ifpObj;
        int perPageCount = 20;
        int videoSize = 5;//5M
        int imgSize = 1;//1M

        static Expression<Func<PetInfo, dynamic>> petInfoFunc;

        static AdminHomeController()
        {
            //生成宠物信息表达式
            petInfoFunc = (x) => new
            {
                petinfoid = x.petinfoid,
                date = x.updatetime.Value.ToString("yyyy-MM-dd HH:mm"),
                nickName = x.nickname,
                breed = x.breed,
                price = x.price,
                stock = x.stock,
                species = speciesinfoDict[x.speciesid ?? 1],
                age = x.age,
                other = $"<span style='font-weight:bold;'>性别：</span>{x.gender} | <span style='font-weight:bold;'>绝育：</span>{x.sterstatus} | " +
                             $"<span style='font-weight:bold;'>疫苗：</span>{x.vaccinstatus} | <span style='font-weight:bold;'>高度：</span>{x.height} | " +
                             $"<span style='font-weight:bold;'>长度：</span>{x.length} | <span style='font-weight:bold;'>体重：</span>{x.weight} | <span style='font-weight:bold;'>备注：</span>{x.remark}",
            };
        }

        public AdminHomeController(MyPetHubContext dbContext, IMemoryCache mcObj, IHttpContextAccessor httpContextAccessor, IFileProvider ifp,IConfiguration configuration) : base(mcObj, dbContext, httpContextAccessor)
        {
            this.ifpObj = ifp;
            perPageCount = configuration.GetValue<int>("PerPageCount");//宠物信息每页数据量
            videoSize = configuration.GetValue<int>("videoSize");//视频大小
            imgSize = configuration.GetValue<int>("imgSize");//图片大小

            //模拟登陆！！！！！！！！！！！！
            //SHA256 mySHA256 = SHA256.Create();
            //string shaPwd = BitConverter.ToString(mySHA256.ComputeHash(UnicodeEncoding.UTF8.GetBytes("123456")));

            //SysUser? suObj = dbContext.SysUser.Where(x => x.merchantid == merID && x.account == "lyptest" && x.password == shaPwd).FirstOrDefault();
            //httpContextAccessor.HttpContext.Session.SetString("SysUser", JsonConvert.SerializeObject(suObj, formatSettings));

            //防止冒充其他的商家
            if (httpContextAccessor.HttpContext.Session.GetString("SysUser") != null)
            {
                SysUser? mm = JsonConvert.DeserializeObject<SysUser>(httpContextAccessor.HttpContext.Session.GetString("SysUser"));
                if (mm.merchantid != merID)
                    throw new Exception("身份验证失败");

                if (mm.adminlevel > 1)
                    throw new Exception("权限验证失败");
            }
        }

        //宠物信息
        [AdminHomeActionFilter]
        public async Task<IActionResult> Index()
        {
            var speciesList = speciesinfoDict.Select(x => new { id = x.Key, name = x.Value }).ToList();
            ViewData["speciesList"] = JsonConvert.SerializeObject(speciesList, formatSettings);

            List<BreedInfo> biObjs = await dbContext.BreedInfo.Where(x => x.merchantid == merID).ToListAsync();
            var breedNames = biObjs.Select(x=>new { id = x.breedid, name = x.name }).ToList();
            ViewData["breedInfo"] = JsonConvert.SerializeObject(breedNames, formatSettings);

            ViewData["pageSize"] = perPageCount;
            ViewData["videoSize"] = videoSize;
            ViewData["imgSize"] = imgSize; 
            ViewData["theDomain"] = subDomain;
            return View();
        }

        [HttpPost]
        public async Task<string> AddOrUpdatePetInfo()
        {
            string returnInfo = "ok";

            //名称重复判断
            JObject jobj = JObject.Parse(Request.Form["petInfo"].ToString());
            string petinfoid = jobj["petinfoid"].ToString();
            string nickName = jobj["nickName"].ToString();
            if (petinfoid == "-1")//添加
            {
                PetInfo petInfo = await dbContext.PetInfo.Where(x => x.merchantid == merID && x.nickname == nickName).FirstOrDefaultAsync();
                if(petInfo != null)
                {
                    return "名称重复";
                }
            }
            else
            {
                PetInfo petInfo = await dbContext.PetInfo.Where(x => x.merchantid == merID && x.nickname == nickName && x.petinfoid != long.Parse(petinfoid)).FirstOrDefaultAsync();
                if (petInfo != null)
                {
                    return "名称重复";
                }
            }

            //文件路径
            string imgPath = ifpObj.GetDirectoryContents(subDomain).Where(x=>x.Name == "imgs").First().PhysicalPath;
            string videoPath = ifpObj.GetDirectoryContents(subDomain).Where(x => x.Name == "videos").First().PhysicalPath;

            string coverImgSrc=null;
            string petVideoSrc = null;
            string otherImgSrc="";

            //过form表单对象获取文件
            for (int i = 0; i < Request.Form.Files.Count; i++)
            {
                string filekey = Request.Form.Files[i].Name;//key值
                string fileOriginalName = Request.Form.Files[i].FileName;
                string newFileName = Guid.NewGuid().ToString() + fileOriginalName.Substring(fileOriginalName.LastIndexOf('.')).ToLower();//新名称

                if (filekey.Contains("coverImg"))
                    coverImgSrc = newFileName;
                else if(filekey.Contains("video"))
                    petVideoSrc = newFileName;
                else if(filekey.Contains("otherImg"))
                    otherImgSrc += (newFileName + "|");

                string pathInfo = "";
                if(filekey.Contains("video"))
                    pathInfo = videoPath;
                else
                    pathInfo = imgPath;

                using (var targetStream = System.IO.File.Create(pathInfo + "/" + newFileName))
                {
                    await Request.Form.Files[i].CopyToAsync(targetStream);
                }
            }

            if (otherImgSrc != "")
                otherImgSrc = otherImgSrc.Substring(0, otherImgSrc.Length-1);

            //保存数据
            using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                PetInfo petInfo;
                if (petinfoid == "-1")//添加
                {
                    petInfo = new PetInfo();
                    petInfo.merchantid = merID;
                    petInfo.petinfoid = long.Parse(DateTime.Now.ToString("yyyyMMddHHmmssfff"));
                    petInfo.videosrc = petVideoSrc;
                }
                else//编辑
                {
                    petInfo = await dbContext.PetInfo.Where(x => x.merchantid == merID && x.petinfoid == long.Parse(petinfoid)).FirstOrDefaultAsync();

                    if(string.IsNullOrEmpty(petVideoSrc))//没有更改视频
                    {
                        DeleteOldFile(petInfo, imgPath, videoPath, false);//不删除视频文件
                    }
                    else
                    {
                        DeleteOldFile(petInfo, imgPath, videoPath, true);
                        petInfo.videosrc = petVideoSrc;
                    }
                }

                SetPetInfoData(petInfo, jobj);
                petInfo.coverimgsrc = coverImgSrc;
                petInfo.otherimgsrc = otherImgSrc;

                //是否新品种
                BreedInfo biObj = await dbContext.BreedInfo.Where(x => x.merchantid == merID && x.name == petInfo.breed).FirstOrDefaultAsync();
                if (biObj == null)
                {
                    BreedInfo newBreedInfo = new BreedInfo();
                    newBreedInfo.merchantid = merID;
                    newBreedInfo.breedid = long.Parse(DateTime.Now.ToString("yyyyMMddHHmmssfff"));
                    newBreedInfo.name = petInfo.breed;
                    await dbContext.BreedInfo.AddAsync(newBreedInfo);

                    returnInfo = "newbreed|" + newBreedInfo.breedid;
                }

                if (petinfoid == "-1")//添加
                {
                    await dbContext.PetInfo.AddAsync(petInfo);
                }

                await dbContext.SaveChangesAsync();
                scope.Complete();
            }
            return returnInfo;
        }

        //json数据赋值到宠物信息对象
        private void SetPetInfoData(PetInfo petInfo, JObject jobj)
        {
            petInfo.nickname = jobj["nickName"].ToString();
            petInfo.price = int.Parse(jobj["price"].ToString());
            petInfo.stock = int.Parse(jobj["stock"].ToString());
            petInfo.speciesid = int.Parse(jobj["selectedSpeciesItem"].ToString());
            petInfo.age = int.Parse(jobj["age"].ToString());
            petInfo.gender = jobj["gender"].ToString() == "1" ? "公" : "母";
            petInfo.height = jobj["height"].ToString() == "" ? null : double.Parse(jobj["height"].ToString());
            petInfo.length = jobj["length"].ToString() == "" ? null : double.Parse(jobj["length"].ToString());
            petInfo.weight = jobj["weight"].ToString() == "" ? null : double.Parse(jobj["weight"].ToString());
            petInfo.sterstatus = jobj["sterStatus"].ToString() == "1" ? "已绝育" : "未绝育";
            petInfo.vaccinstatus = jobj["vaccStatus"].ToString() == "1" ? "已接种" : "未接种";
            petInfo.remark = jobj["remark"].ToString();
            petInfo.breed = jobj["breed"].ToString();
            petInfo.updatetime = DateTime.Now;
        }

        //删除宠物信息
        [HttpPost]
        public async Task<string> DeletePetInfo([FromBody] object json)
        {
            //名称重复判断
            JObject jobj = JObject.Parse(json.ToString());
            string petInfoIDs = jobj["petInfoIDs"].ToString();
            string[] idArray = petInfoIDs.Split('|');

            //文件路径
            string imgPath = ifpObj.GetDirectoryContents(subDomain).Where(x => x.Name == "imgs").First().PhysicalPath;
            string videoPath = ifpObj.GetDirectoryContents(subDomain).Where(x => x.Name == "videos").First().PhysicalPath;

            List<PetInfo> pis = new List<PetInfo>();
            foreach (string id in idArray)
            {
                var petInfo = await dbContext.PetInfo.Where(x => x.merchantid == merID && x.petinfoid == long.Parse(id)).FirstOrDefaultAsync();
                DeleteOldFile(petInfo, imgPath, videoPath);

                pis.Add(petInfo);
            }

            dbContext.PetInfo.RemoveRange(pis);
            await dbContext.SaveChangesAsync();

            return "ok";
        }

        //宠物信息分页
        [HttpPost]
        public async Task<JsonResult> GetPaginationInfo([FromBody] object json)
        {
            JObject jobj = JObject.Parse(json.ToString());
            int pageNum = int.Parse(jobj["pageNum"].ToString());
            string breedOrNickName = jobj["breedOrNickName"].ToString();
            int specialsNum = int.Parse(jobj["specialsNum"].ToString());

            PaginationData<List<dynamic>> paginationData = new PaginationData<List<dynamic>>();
            List<dynamic> petInfo;
            int dataCount = 0;
            if (specialsNum == 0)//全部种类
            {
                if (string.IsNullOrEmpty(breedOrNickName))//无搜索条件
                {
                    dataCount = await dbContext.PetInfo.Where(x => x.merchantid == merID).CountAsync();
                    petInfo = await dbContext.PetInfo.Where(x => x.merchantid == merID).OrderByDescending(x => x.updatetime).Skip((pageNum - 1) * perPageCount).Take(perPageCount).Select(petInfoFunc).ToListAsync();
                }
                else
                {
                    dataCount = await dbContext.PetInfo.Where(x => x.merchantid == merID && (x.breed.Contains(breedOrNickName) || x.nickname.Contains(breedOrNickName))).CountAsync();
                    petInfo = await dbContext.PetInfo.Where(x => x.merchantid == merID && (x.breed.Contains(breedOrNickName) || x.nickname.Contains(breedOrNickName))).OrderByDescending(x => x.updatetime)
                            .Skip((pageNum - 1) * perPageCount).Take(perPageCount).Select(petInfoFunc).ToListAsync();
                }
            }
            else
            {
                if (string.IsNullOrEmpty(breedOrNickName))//无搜索条件
                {
                    dataCount = await dbContext.PetInfo.Where(x => x.merchantid == merID && x.speciesid == specialsNum).CountAsync();
                    petInfo = await dbContext.PetInfo.Where(x => x.merchantid == merID && x.speciesid == specialsNum).OrderByDescending(x => x.updatetime)
                     .Skip((pageNum - 1) * perPageCount).Take(perPageCount).Select(petInfoFunc).ToListAsync();
                }
                else
                {
                    dataCount = await dbContext.PetInfo.Where(x => x.merchantid == merID && x.speciesid == specialsNum && (x.breed.Contains(breedOrNickName) || x.nickname.Contains(breedOrNickName))).CountAsync();
                    petInfo = await dbContext.PetInfo.Where(x => x.merchantid == merID && x.speciesid == specialsNum && (x.breed.Contains(breedOrNickName) || x.nickname.Contains(breedOrNickName))).OrderByDescending(x => x.updatetime)
                         .Skip((pageNum - 1) * perPageCount).Take(perPageCount).Select(petInfoFunc).ToListAsync();
                }
            }

            paginationData.data = petInfo;
            paginationData.dataCount = dataCount;

            return new JsonResult(paginationData);
        }

        [HttpPost]
        public async Task<ActionResult> GetPetInfoByID([FromBody] object json)
        {
            JObject jobj = JObject.Parse(json.ToString());
            long petinfoID = long.Parse(jobj["petinfoID"].ToString());

            PetInfo petInfo = await dbContext.PetInfo.Where(x => x.merchantid == merID && x.petinfoid == petinfoID).FirstOrDefaultAsync();
            return new JsonResult(petInfo);
        }

        //宠物寄养
        [AdminHomeActionFilter]
        public IActionResult PetFosterage()
        {
            ViewData["Title"] = "宠物寄养";
            ViewData["notice"] = "寄养公告";
            ViewData["datatype"] = 0;
            ViewData["videoSize"] = videoSize;
            ViewData["imgSize"] = imgSize;

            ViewData["defaultMenuActive"] = 2;
            ViewData["theDomain"] = subDomain;
            return View();
        }

        //添加或修改寄养公告
        [HttpPost]
        public async Task<string> AddOrUpdatePetFosterageInfo()
        {
            //文件路径
            string imgPath = ifpObj.GetDirectoryContents(subDomain).Where(x => x.Name == "imgs").First().PhysicalPath;
            string videoPath = ifpObj.GetDirectoryContents(subDomain).Where(x => x.Name == "videos").First().PhysicalPath;

            string petVideoSrc = null;
            string otherImgSrc = "";

            //过form表单对象获取文件
            for (int i = 0; i < Request.Form.Files.Count; i++)
            {
                string filekey = Request.Form.Files[i].Name;//key值
                string fileOriginalName = Request.Form.Files[i].FileName;
                string newFileName = Guid.NewGuid().ToString() + fileOriginalName.Substring(fileOriginalName.LastIndexOf('.')).ToLower();//新名称

                if (filekey.Contains("video"))
                    petVideoSrc = newFileName;
                else if (filekey.Contains("otherImg"))
                    otherImgSrc += (newFileName + "|");

                string pathInfo = "";
                if (filekey.Contains("video"))
                    pathInfo = videoPath;
                else
                    pathInfo = imgPath;

                using (var targetStream = System.IO.File.Create(pathInfo + "/" + newFileName))
                {
                    await Request.Form.Files[i].CopyToAsync(targetStream);
                }
            }

            if (otherImgSrc != "")
                otherImgSrc = otherImgSrc.Substring(0, otherImgSrc.Length - 1);

            JObject jobj = JObject.Parse(Request.Form["textData"].ToString());
            string petfosterageid = jobj["petfosterageid"].ToString();
            string content = jobj["content"].ToString();
            int datatype = int.Parse(jobj["datatype"].ToString());

            PetFosterage pfObj;
            if (petfosterageid == "-1")//添加
            {
                pfObj = new PetFosterage();
                pfObj.merchantid = merID;
                pfObj.petfosterageid = long.Parse(DateTime.Now.ToString("yyyyMMddHHmmssfff"));
                pfObj.datatype = datatype;
                pfObj.videosrc = petVideoSrc;
            }
            else//编辑
            {
                pfObj = await dbContext.PetFosterage.Where(x => x.merchantid == merID && x.petfosterageid == long.Parse(petfosterageid)).FirstOrDefaultAsync();

                if (string.IsNullOrEmpty(petVideoSrc))//没有更改视频
                {
                    DeleteOldFile(pfObj, imgPath, videoPath, false);//不删除视频文件
                }
                else
                {
                    DeleteOldFile(pfObj, imgPath, videoPath, true);
                    pfObj.videosrc = petVideoSrc;
                }
            }

            pfObj.content = content;
            pfObj.imgsrcs = otherImgSrc;
            pfObj.updatetime = DateTime.Now;

            if (petfosterageid == "-1")//添加
            {
                await dbContext.PetFosterage.AddAsync(pfObj);
            }

            await dbContext.SaveChangesAsync();

            return "ok";
        }

        [HttpPost]
        public async Task<ActionResult> GetPetFosterage([FromBody] object json)
        {
            JObject jobj = JObject.Parse(json.ToString());
            int datatype = int.Parse(jobj["datatype"].ToString());

            PetFosterage petFosterage = await dbContext.PetFosterage.Where(x => x.merchantid == merID && x.datatype == datatype).FirstOrDefaultAsync();
            return new JsonResult(petFosterage);
        }

        //宠物美容
        [AdminHomeActionFilter]
        public IActionResult PetBeauty()
        {
            ViewData["Title"] = "宠物美容";
            ViewData["notice"] = "美容公告";
            ViewData["datatype"] = 1;
            ViewData["videoSize"] = videoSize;
            ViewData["imgSize"] = imgSize;

            ViewData["defaultMenuActive"] = 3;
            ViewData["theDomain"] = subDomain;
            return View("PetFosterage");
        }

        //联系我们
        [AdminHomeActionFilter]
        public IActionResult ContactUS()
        {
            ViewData["videoSize"] = videoSize;
            ViewData["imgSize"] = imgSize;
            ViewData["theDomain"] = subDomain;
            return View();
        }

        [HttpPost]
        public async Task<ActionResult> GetAboutUS()
        {
            AboutUS ausOBj = await dbContext.AboutUS.Where(x => x.merchantid == merID).FirstOrDefaultAsync();
            return new JsonResult(ausOBj);
        }

        //添加或修改联系方式
        [HttpPost]
        public async Task<string> AddOrUpdateContactInfo()
        {
            //文件路径
            string imgPath = ifpObj.GetDirectoryContents(subDomain).Where(x => x.Name == "imgs").First().PhysicalPath;
            string videoPath = ifpObj.GetDirectoryContents(subDomain).Where(x => x.Name == "videos").First().PhysicalPath;

            string coverImgSrc = null;
            string videoSrc = null;
            string otherImgSrc = "";

            //过form表单对象获取文件
            for (int i = 0; i < Request.Form.Files.Count; i++)
            {
                string filekey = Request.Form.Files[i].Name;//key值
                string fileOriginalName = Request.Form.Files[i].FileName;
                string newFileName = Guid.NewGuid().ToString() + fileOriginalName.Substring(fileOriginalName.LastIndexOf('.')).ToLower();//新名称

                if (filekey.Contains("coverImg"))
                    coverImgSrc = newFileName;
                else if (filekey.Contains("video"))
                    videoSrc = newFileName;
                else if (filekey.Contains("otherImg"))
                    otherImgSrc += (newFileName + "|");

                string pathInfo = "";
                if (filekey.Contains("video"))
                    pathInfo = videoPath;
                else
                    pathInfo = imgPath;

                using (var targetStream = System.IO.File.Create(pathInfo + "/" + newFileName))
                {
                    await Request.Form.Files[i].CopyToAsync(targetStream);
                }
            }

            if (otherImgSrc != "")
                otherImgSrc = otherImgSrc.Substring(0, otherImgSrc.Length - 1);

            JObject jobj = JObject.Parse(Request.Form["textData"].ToString());
            string aboutusid = jobj["aboutusid"].ToString();
            string shopName = jobj["shopName"].ToString();
            string address = jobj["address"].ToString();
            string phone = jobj["phone"].ToString();
            string email = jobj["email"].ToString();
            string contact = jobj["contact"].ToString();
            string introduce = jobj["introduce"].ToString();

            AboutUS ausObj;
            if (aboutusid == "-1")//添加
            {
                ausObj = new AboutUS();
                ausObj.merchantid = merID;
                ausObj.aboutusid = long.Parse(DateTime.Now.ToString("yyyyMMddHHmmssfff"));
                ausObj.videosrc = videoSrc;
            }
            else//编辑
            {
                ausObj = await dbContext.AboutUS.Where(x => x.merchantid == merID && x.aboutusid == long.Parse(aboutusid)).FirstOrDefaultAsync();
                DeleteOldFile(ausObj, imgPath, videoPath);
                if (string.IsNullOrEmpty(videoSrc))//没有更改视频
                {
                    DeleteOldFile(ausObj, imgPath, videoPath, false);//不删除视频文件
                }
                else
                {
                    DeleteOldFile(ausObj, imgPath, videoPath, true);
                    ausObj.videosrc = videoSrc;
                }
            }

            ausObj.merchantname = shopName;
            ausObj.contact = contact;
            ausObj.address = address;
            ausObj.email = email;
            ausObj.phone = phone;
            ausObj.introduce = introduce;
            ausObj.coverimgsrc = coverImgSrc;
            ausObj.otherimgsrc = otherImgSrc;
            ausObj.updatetime = DateTime.Now;

            if (aboutusid == "-1")//添加
            {
                await dbContext.AboutUS.AddAsync(ausObj);
            }

            await dbContext.SaveChangesAsync();

            return "ok";
        }

        //获取文件
        [HttpPost]
        public ActionResult DownFile([FromBody] object json)
        {
            JObject jobj = JObject.Parse(json.ToString());
            string fileName = jobj["fileName"].ToString();
            string lastName = fileName.Substring(fileName.LastIndexOf('.')).ToLower();//后缀名

            string filePath = "";
            if (allowedImgList.Contains(lastName))
            {
                filePath = ifpObj.GetDirectoryContents(subDomain).Where(x => x.Name == "imgs").First().PhysicalPath;
            }
            else if (allowedVideoList.Contains(lastName))
            {
                filePath = ifpObj.GetDirectoryContents(subDomain).Where(x => x.Name == "videos").First().PhysicalPath;
            }

            using (var stream = new FileStream(filePath + "/" + fileName, FileMode.Open))
            {
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                stream.Seek(0, SeekOrigin.Begin); // 设置当前流的位置为流的开始

                return new FileContentResult(bytes, "application/octet-stream");
            }
        }

        //更改账号
        [ValidateAntiForgeryToken]
        [HttpPost]
        public async Task<string> ChangeAccount([FromBody] object json)
        {
            JObject jobj = JObject.Parse(json.ToString());
            string nickName = jobj["nickName"].ToString();
            string oldPassward = jobj["oldPassward"].ToString();
            string newPassward = jobj["newPassward"].ToString();

            string shaPwd = BitConverter.ToString(SHA256.Create().ComputeHash(UnicodeEncoding.UTF8.GetBytes(oldPassward)));

            SysUser? sysUser = JsonConvert.DeserializeObject<SysUser>(HttpContext.Session.GetString("SysUser"));
            if (sysUser.password != shaPwd)
                return "身份验证失败";

            SysUser? suObj = await dbContext.SysUser.Where(x => x.merchantid == merID && x.account == sysUser.account && x.password == shaPwd).FirstOrDefaultAsync();
            if (suObj == null)
            {
                return "用户名或密码错误";
            }

            if (suObj.status != 0)
            {
                return "账号已被禁用";
            }

            suObj.nickname = nickName;
            suObj.password = string.IsNullOrEmpty(newPassward) ? suObj.password : BitConverter.ToString(SHA256.Create().ComputeHash(UnicodeEncoding.UTF8.GetBytes(newPassward)));
            await dbContext.SaveChangesAsync();

            HttpContext.Session.SetString("SysUser", JsonConvert.SerializeObject(suObj, formatSettings));
            return "ok";
        }

        //登录提交
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        [HttpPost]
        public async Task<string> Login([FromBody] LoginInfoVM liVM)
        {
            string verifyCode = HttpContext.Session.GetString("VerifyCode");
            if (liVM.VerificationCode.ToUpper() != verifyCode)
            {
                return "验证码错误";
            }

            SHA256 mySHA256 = SHA256.Create();
            string shaPwd = BitConverter.ToString(mySHA256.ComputeHash(UnicodeEncoding.UTF8.GetBytes(liVM.UserPwd)));

            SysUser? suObj = await dbContext.SysUser.Where(x =>x.merchantid == merID && x.account == liVM.UserName && x.password == shaPwd).FirstOrDefaultAsync();
            if (suObj == null)
            {
                return "用户名或密码错误";
            }

            if(suObj.status != 0)
            {
                return "账号已被禁用";
            }

            HttpContext.Session.SetString("SysUser", JsonConvert.SerializeObject(suObj, formatSettings));
            return "ok"; 
        }

        //退出登录
        [ValidateAntiForgeryToken]
        [HttpPost]
        public string Logout()
        {
            HttpContext.Session.Remove("SysUser");
            return "ok";
        }

        //登录页面
        [AllowAnonymous]
        [HttpGet]
        public IActionResult Login()
        {
            string returnUrl = Request.Query["returnUrl"].ToString();
            if (string.IsNullOrEmpty(returnUrl))
                returnUrl = "/admin";

            if (!returnUrl.StartsWith('/'))
                throw new Exception($"返回路径错误:{returnUrl}");

            ViewData["returnUrl"] = returnUrl;
            return View();
        }

        //获取验证码
        [AllowAnonymous]
        [HttpGet]
        public async Task<FileResult> GetVerifyCode()
        {
            var oldVerifyCode = HttpContext.Session.GetString("VerifyCode");
            if (!string.IsNullOrEmpty(oldVerifyCode))
            {
                HttpContext.Session.SetString("VerifyCode", "");
            }
            return await Task.Factory.StartNew(() =>
            {
                VerifyCode verifyCode = VerifyCodeHelper.CreateVerifyCode(4, VerifyCodeType.CHAR);
                HttpContext.Session.SetString("VerifyCode", verifyCode.Code.ToUpper());
                return File(verifyCode.Image, @"image/jpeg"); ;
            });
        }

    }
}
